import Package from './Package.js'

function getUsers(params) {
  const app = getApp();
  var temp = {};
  if (!params.account) temp.account = app && app.userInfo && app.userInfo.userId || "";
  if (!params.befocusedAccount) temp.befocusedAccount = app && app.userInfo && app.userInfo.userId || "";
  if (!params.userId) temp.userId = app && app.userInfo && app.userInfo.userId || "";
  if (!params.sender) temp.sender = app && app.userInfo && app.userInfo.userId || "";
  if (!params.operator) temp.operator = app && app.userInfo && app.userInfo.userId || "";
  if (!params.releaseAccount) temp.releaseAccount = app && app.userInfo && app.userInfo.userId || "";

  // if (!params.account) temp.account = '4ea044a060344226942e6a3619d3ceee';
  // if (!params.befocusedAccount) temp.befocusedAccount = '4ea044a060344226942e6a3619d3ceee';
  // if (!params.userId) temp.userId = '4ea044a060344226942e6a3619d3ceee';
  // if (!params.sender) temp.sender = '4ea044a060344226942e6a3619d3ceee';
  // if (!params.operator) temp.operator = '4ea044a060344226942e6a3619d3ceee';
  // if (!params.releaseAccount) temp.releaseAccount = '4ea044a060344226942e6a3619d3ceee';
  temp.wxMold = app.appType;
  return temp;
}

function getServicesAddr() {
  return Package.getPackage().domain;
}

function getVideoDomain() {
  return Package.getPackage().videoDomain;
}

/**
 * 内置地图查看位置
 */
function openLocation(data) {
  wx.openLocation({
    latitude: data.latitude,
    longitude: data.longitude,
  })
}

/**
 * 获取data值
 * that 作用域
 * key 需要获取值的key
 */
function getData(that, key) {
  return that.data[key];
}

/**
 * 设置data值
 * that 作用域
 * valueObj [Object] 需要设置到data的所有值
 * callback setData引起的界面更新渲染完毕后的回调函数
 */
function setData(that, valueObj, callback) {
  that.setData(valueObj, function() {
    if (callback) callback();
  })
}

/**
 * 子组件传递数据到父组件
 * that 作用域
 * key  传递中间key
 * vakue  传递值
 */
function emit(that, key, value) {
  that.triggerEvent(key, value);
}

/**
 * 获取页面点击事件参数
 * event 事件参数
 * key 需要获取的key
 */
function getParam(event, key) {
  return event.currentTarget.dataset[key];
}

/**
 * 保持屏幕常亮
 */
function setKeepScreenOn() {
  if (wx.setKeepScreenOn) {
    wx.setKeepScreenOn({
      keepScreenOn: true
    });
  }
}

/**
 * 设置缓存
 * @key String 缓存名
 * @value  缓存数据
 */
function setStorageSync(key, value) {
  wx.setStorageSync(key, value);
}

/**
 * 获取缓存
 * @key String 缓存名
 */
function getStorageSync(key) {
  return wx.getStorageSync(key);
}

/**
 * 弹框提示
 * @param msg [提示内容]
 * param dur [提示的延迟时间]
 * param logo [提示图标]
 * param img [提示自定义图标路径]
 */
function showToast(msg, dur, logo, img) {
  var duration = dur || 1500;
  var icon = logo || "none";
  var image = img || false;
  var data = {
    title: msg,
    mask: true,
    duration: duration,
    icon: icon,
  }
  if (image) {
    data.image = image;
  }
  wx.showToast(data);
}

/**
 * 模态框提示
 * @param data Object
 * @param data.content [提示内容]
 * param  data.title  [提示标题]
 * param  data.showCancel [是否显示取消按钮]
 * param  data.cancelText [取消按钮文字]
 * param  data.confirmText  [确定按钮文字]
 * param  data.success()  Function
 */
function showModal(data) {
  wx.showModal({
    title: data.title || '提示',
    content: data.content,
    showCancel: data.showCancel || false,
    cancelText: data.cancelText || "取消",
    confirmText: data.confirmText || "确定",
    success: function(res) {
      if (res.cancel) {
        if (data.cancel) data.cancel();
      } else if (res.confirm) {
        if (data.confirm) data.confirm();
      }
    }
  })
}

/**
 * 微信扫码
 * @param data Object
 *        data.success 成功回调
 *        data.fail 失败回调
 */
function scanCode(data) {
  wx.scanCode({
    success: function(res) {
      data.success(res);
    },
    fail: function(res) {
      data.fail();
    }
  })
}

// 接口请求
var requestAjax = function(data, wrongs = 0) {
  // 弹框提示
  if (!data.cancelToast) {
    wx.showLoading({
      title: data.toastText || '请稍等..',
      mask: true,
    })
  }
  var url = data.url || getServicesAddr() + (data.serAddr ? data.serAddr : '');

  var reqData = data.data || {};
  Object.assign(reqData, getUsers(reqData) || {});
  console.warn("请求参数", url, reqData);
  wx.request({
    url: url,
    data: reqData,
    method: data.method || 'POST',
    header: data.header || {},
    success: function(res) {
      console.log("请求成功返回", url, res);
      let xbody = res.data || {};
      let resMessage = xbody[Package.getPackage().resMsgKey];
      let resStatus = xbody[Package.getPackage().resStatusKey];

      // 处理结束，取消弹框
      if (!data.cancelToast) wx.hideLoading();
      xbody.msg = resMessage || "操作失败";
      if (resStatus == Package.getPackage().resStatus.ok) {
        xbody.success = true;
        // 成功返回
        if (data.success) data.success(xbody)
      } else {
        xbody.fail = true;
        // 失败返回
        if (data.fail) data.fail(xbody)
      }
      if (data.complete) data.complete(xbody);
    },
    fail: function(res) {
      wx.hideLoading()
      console.log('requestAjax fail===>', res)

      // 处理结束，取消弹框
      if (!data.cancelToast) wx.hideLoading();
      if (wrongs == 0) {
        // 失败返回
        if (data.fail) data.fail({
          msg: "操作失败"
        })
        if (data.complete) data.complete({
          msg: "操作失败"
        });
        if (data.netTimeout) data.netTimeout();
      }
      // requestAjax(data,1);
    },
    complete: function(res) {
      wx.hideLoading()
    }
  })
}

/**
 * 获取年月日
 * params num 与当天时间的差值
 * params tempDate 直接设置日期
 */
function time(num, tempDate) {
  var n = num || 0;
  var chnNumChar = ["日", "一", "二", "三", "四", "五", "六"];
  var date;

  if (tempDate) {
    tempDate = tempDate.trim();
    if ((typeof tempDate) == 'string') {
      var temp = tempDate.split(' ');
      var arr = [],
        temp1 = '',
        temp2 = '';
      if (temp[0]) temp1 = temp[0].split('-');
      if (temp[1]) temp2 = temp[1].split(':');
      if (temp1.length > 0) {
        if (temp1[1]) temp1[1] = temp1[1] - 1;
        arr = arr.concat(temp1);
      }
      if (temp2.length > 0) arr = arr.concat(temp2);
      date = new Date(...arr);
    } else {
      date = new Date(tempDate);
    }
  } else {
    date = new Date();
  }

  date.setDate(date.getDate() + n);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var week = date.getDay();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  var msec = date.getTime();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  if (minute < 10) {
    minute = '0' + minute;
  }

  var typeA = Number(month) + '月' + Number(day) + '日';
  var typeB = year + '-' + month + '-' + day;
  var typeC = (hour < 10 ? '0' + hour : hour) + ':' + minute + ":" + (second < 10 ? '0' + second : second);
  var typeD = typeB + " " + typeC;

  return {
    typeA: typeA,
    typeB: typeB,
    typeC: typeC,
    typeD: typeD,
    year: year,
    month: month,
    day: day,
    week: week,
    weekText: chnNumChar[week],
    hour: hour,
    minute: minute,
    msec: msec, //毫秒
    dayMsec: 1000 * 60 * 60 * 24, //一天的毫秒
  };
}

/**
 * 手机号正则校验
 * params phone 手机号
 */
function isPoneAvailable(phone) {
  var myreg = /^[1][0-9]{10}$/;
  if (!myreg.test(phone)) {
    return false;
  } else {
    return true;
  }
}

// 暴露方法
export default {
  openLocation,
  getData,
  setData,
  getVideoDomain,
  emit,
  getParam,
  setKeepScreenOn,
  setStorageSync,
  getStorageSync,
  showToast,
  showModal,
  scanCode,
  requestAjax,
  time,
  isPoneAvailable,
}